package com.yjz.zpay.utils;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.app.ActivityManager.RunningTaskInfo;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;

import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.HttpHeaders;
import com.lzy.okgo.model.Response;
import com.yjz.zpay.db.DBManager;
import com.yjz.zpay.ui.CustomApplcation;
import com.yjz.zpay.ui.MainActivity;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import de.robv.android.xposed.XposedHelpers;

/**
 * @author yjz
 *         created at 2019/1/17 下午9:16
 */

public class PayHelperUtils {

    /**
     * 转账到银行卡
     */
    public static final String Action_SaveSpParams = "com.yjz.save.params";

    public static String WECHATSTART_ACTION = "com.payhelper.wechat.start";
    public static String ALIPAYSTART_ACTION = "com.payhelper.alipay.start";
    public static String QQSTART_ACTION = "com.payhelper.qq.start";
    public static String MSGRECEIVED_ACTION = "com.tools.payhelper.msgreceived";
    public static String TRADENORECEIVED_ACTION = "com.tools.payhelper.tradenoreceived";
    public static String LOGINIDRECEIVED_ACTION = "com.tools.payhelper.loginidreceived";
    public static String GET_PERSON_MOENY_NOTICE = "GET_PERSON_MOENY_NOTICE";

    /*
     * 启动一个app
     */
    public static void startAPP() {
        try {
            Intent intent = new Intent(CustomApplcation.getInstance().getApplicationContext(), MainActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            CustomApplcation.getInstance().getApplicationContext().startActivity(intent);
        } catch (Exception e) {
        }
    }

    /**
     * 将图片转换成Base64编码的字符串
     *
     * @param path
     * @return base64编码的字符串
     */
    public static String imageToBase64(String path) {
        if (TextUtils.isEmpty(path)) {
            return null;
        }
        InputStream is = null;
        byte[] data = null;
        String result = null;
        try {
            is = new FileInputStream(path);
            // 创建一个字符流大小的数组。
            data = new byte[is.available()];
            // 写入数组
            is.read(data);
            // 用默认的编码格式进行编码
            result = Base64.encodeToString(data, Base64.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
        result = "\"data:image/gif;base64," + result + "\"";
        return result;
    }

    public static void sendAppMsg(String money, String mark, String type, Context context) {
        Intent broadCastIntent = new Intent();
        if (type.equals("alipay")) {
            broadCastIntent.setAction(ALIPAYSTART_ACTION);
        } else if (type.equals("wechat")) {
            broadCastIntent.setAction(WECHATSTART_ACTION);
        } else if (type.equals("qq")) {
            broadCastIntent.setAction(QQSTART_ACTION);
        }
        broadCastIntent.putExtra("mark", mark);
        broadCastIntent.putExtra("money", money);
        context.sendBroadcast(broadCastIntent);
    }

    /*
     * 将时间戳转换为时间
     */
    public static String stampToDate(String s) {
        String res;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        long lt = Long.parseLong(s);
        Date date = new Date(lt * 1000);
        res = simpleDateFormat.format(date);
        return res;
    }

    /**
     * 方法描述：判断某一应用是否正在运行
     *
     * @param context     上下文
     * @param packageName 应用的包名
     * @return true 表示正在运行，false表示没有运行
     */
    public static boolean isAppRunning(Context context, String packageName) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<RunningTaskInfo> list = am.getRunningTasks(100);
        if (list.size() <= 0) {
            return false;
        }
        for (RunningTaskInfo info : list) {
            if (info.baseActivity.getPackageName().equals(packageName)) {
                return true;
            }
        }
        return false;
    }

    /*
     * 启动一个app
     */
    public static void startAPP(Context context, String appPackageName) {
        try {
            Intent intent = context.getPackageManager().getLaunchIntentForPackage(appPackageName);
            context.startActivity(intent);
        } catch (Exception e) {
            sendmsg(context, "startAPP异常" + e.getMessage());
        }
    }

    public static void notify(final Context context, String type, final String no, String money, String mark,
                              String dt) {
        String notifyurl = SpUtils.getString(context, "notifyurl");
        String signkey = SpUtils.getString(context, "signkey");
        sendmsg(context, "订单" + no + "重试发送异步通知...");
        if (TextUtils.isEmpty(notifyurl) || TextUtils.isEmpty(signkey)) {
            sendmsg(context, "发送异步通知异常，异步通知地址为空");
            update(no, "异步通知地址为空");
            return;
        }

        String account = "";
        if (type.equals("alipay")) {
            account = SpUtils.getString(context, "alipay");
        } else if (type.equals("wechat")) {
            account = SpUtils.getString(context, "wechat");
        } else if (type.equals("qq")) {
            account = SpUtils.getString(context, "qq");
        }

        /*HttpUtils httpUtils = new HttpUtils(15000);

        String sign = MD5.md5(dt + mark + money + no + type + signkey);
        RequestParams params = new RequestParams();
        params.addBodyParameter("type", type);
        params.addBodyParameter("no", no);
        params.addBodyParameter("money", money);
        params.addBodyParameter("mark", mark);
        params.addBodyParameter("dt", dt);
        if (!TextUtils.isEmpty(account)) {
            params.addBodyParameter("account", account);
        }
        params.addBodyParameter("sign", sign);
        httpUtils.send(HttpMethod.POST, notifyurl, params, new RequestCallBack<String>() {

            @Override
            public void onFailure(HttpException arg0, String arg1) {
                sendmsg(context, "发送异步通知异常，服务器异常" + arg1);
                update(no, arg1);
            }

            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                String result = arg0.result;
                if (result.contains("success")) {
                    sendmsg(context, "发送异步通知成功，服务器返回" + result);
                } else {
                    sendmsg(context, "发送异步通知失败，服务器返回" + result);
                }
                update(no, result);
            }
        });*/
    }

    private static void update(String no, String result) {
        DBManager dbManager = new DBManager(CustomApplcation.getInstance().getApplicationContext());
        dbManager.updateOrder(no, result);
    }

    public static String getCookieStr(ClassLoader appClassLoader) {
        String cookieStr = "";
        // 获得cookieStr
        XposedHelpers.callStaticMethod(XposedHelpers.findClass(
                "com.alipay.mobile.common.transportext.biz.appevent.AmnetUserInfo", appClassLoader), "getSessionid");
        Context context = (Context) XposedHelpers.callStaticMethod(XposedHelpers.findClass(
                "com.alipay.mobile.common.transportext.biz.shared.ExtTransportEnv", appClassLoader), "getAppContext");
        if (context != null) {
            Object readSettingServerUrl = XposedHelpers.callStaticMethod(
                    XposedHelpers.findClass("com.alipay.mobile.common.helper.ReadSettingServerUrl", appClassLoader),
                    "getInstance");
            if (readSettingServerUrl != null) {
                // String gWFURL = (String)
                // XposedHelpers.callMethod(readSettingServerUrl, "getGWFURL",
                // context);
                String gWFURL = ".alipay.com";
                cookieStr = (String) XposedHelpers.callStaticMethod(XposedHelpers
                                .findClass("com.alipay.mobile.common.transport.http.GwCookieCacheHelper", appClassLoader),
                        "getCookie", gWFURL);
            } else {
                sendmsg(context, "异常readSettingServerUrl为空");
            }
        } else {
            sendmsg(context, "异常context为空");
        }
        return cookieStr;
    }


    public static void sendBroadcastAgencyQr(final Context context, final String money, String alipayId) {
        Intent broadCastIntent = new Intent();
        broadCastIntent.putExtra("money", money);
        broadCastIntent.putExtra("alipayId", alipayId);
        broadCastIntent.setAction(TRADENORECEIVED_ACTION);
        context.sendBroadcast(broadCastIntent);
    }


    public static void getTradeInfo(final Context context, final String cookie) {
        long current = System.currentTimeMillis();
        long s = current - 864000000;
        String c = getCurrentDate();
        String url = "https://mbillexprod.alipay.com/enterprise/simpleTradeOrderQuery.json?beginTime=" + s
                + "&limitTime=" + current + "&pageSize=20&pageNum=1&channelType=ALL";

        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.put("Cookie", cookie);
        httpHeaders.put("Referer", "https://render.alipay.com/p/z/merchant-mgnt/simple-order.html?beginTime=" + c
                + "&endTime=" + c + "&fromBill=true&channelType=ALL");
        OkGo.<String>get(url)
                .headers(httpHeaders)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        Log.d("##########--->账单接口返回-->", result);
                        try {
                            JSONObject jsonObject = new JSONObject(result);
                            JSONObject res = jsonObject.getJSONObject("result");
                            JSONArray jsonArray = res.getJSONArray("list");

//                            if (jsonArray != null && jsonArray.length() > 0) {
//                                // for (int i = 0; i < jsonArray.length(); i++) {
//                                // JSONObject object=jsonArray.getJSONObject(i);
//                                // String tradeNo=object.getString("tradeNo");
//                                // Intent broadCastIntent = new Intent();
//                                // broadCastIntent.putExtra("tradeno", tradeNo);
//                                // broadCastIntent.putExtra("cookie", cookie);
//                                // broadCastIntent.setAction(TRADENORECEIVED_ACTION);
//                                // context.sendBroadcast(broadCastIntent);
//                                // }
//                                JSONObject object = jsonArray.getJSONObject(0);
//                                String tradeNo = object.getString("tradeNo");
//                                Intent broadCastIntent = new Intent();
//                                broadCastIntent.putExtra("tradeno", tradeNo);
//                                broadCastIntent.putExtra("cookie", cookie);
//                                broadCastIntent.setAction(TRADENORECEIVED_ACTION);
//                                context.sendBroadcast(broadCastIntent);
//                            }

                        } catch (Exception e) {
                            sendmsg(context, "getTradeInfo异常" + e.getMessage());
                        }

                    }
                });


        /*HttpUtils httpUtils = new HttpUtils(15000);
        httpUtils.configResponseTextCharset("GBK");
        RequestParams params = new RequestParams();
        params.addHeader("Cookie", cookie);
        params.addHeader("Referer", "https://render.alipay.com/p/z/merchant-mgnt/simple-order.html?beginTime=" + c
                + "&endTime=" + c + "&fromBill=true&channelType=ALL");
        httpUtils.send(HttpMethod.GET, url, params, new RequestCallBack<String>() {

            @Override
            public void onFailure(HttpException arg0, String arg1) {
                sendmsg(context, "服务器异常" + arg1);
            }

            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                String result = arg0.result;
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    JSONObject res = jsonObject.getJSONObject("result");
                    JSONArray jsonArray = res.getJSONArray("list");

                    if (jsonArray != null && jsonArray.length() > 0) {
                        // for (int i = 0; i < jsonArray.length(); i++) {
                        // JSONObject object=jsonArray.getJSONObject(i);
                        // String tradeNo=object.getString("tradeNo");
                        // Intent broadCastIntent = new Intent();
                        // broadCastIntent.putExtra("tradeno", tradeNo);
                        // broadCastIntent.putExtra("cookie", cookie);
                        // broadCastIntent.setAction(TRADENORECEIVED_ACTION);
                        // context.sendBroadcast(broadCastIntent);
                        // }
                        JSONObject object = jsonArray.getJSONObject(0);
                        String tradeNo = object.getString("tradeNo");
                        Intent broadCastIntent = new Intent();
                        broadCastIntent.putExtra("tradeno", tradeNo);
                        broadCastIntent.putExtra("cookie", cookie);
                        broadCastIntent.setAction(TRADENORECEIVED_ACTION);
                        context.sendBroadcast(broadCastIntent);
                    }

                } catch (Exception e) {
                    sendmsg(context, "getTradeInfo异常" + e.getMessage());
                }

            }
        });*/
    }

    public static String getCurrentDate() {
        long l = System.currentTimeMillis();
        Date date = new Date(l);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String d = dateFormat.format(date);
        return d;
    }

    public static void sendmsg(Context context, String msg) {
        Intent broadCastIntent = new Intent();
        broadCastIntent.putExtra("msg", msg);
        broadCastIntent.setAction(MSGRECEIVED_ACTION);
        context.sendBroadcast(broadCastIntent);
    }

    /**
     * 获取当前本地apk的版本
     *
     * @param mContext
     * @return
     */
    public static int getVersionCode(Context mContext) {
        int versionCode = 0;
        try {
            // 获取软件版本号，对应AndroidManifest.xml下android:versionCode
            versionCode = mContext.getPackageManager().getPackageInfo(mContext.getPackageName(), 0).versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            sendmsg(mContext, "getVersionCode异常" + e.getMessage());
        }
        return versionCode;
    }

    /**
     * 获取版本号名称
     *
     * @param context 上下文
     * @return
     */
    public static String getVerName(Context context) {
        String verName = "";
        try {
            verName = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName;
        } catch (PackageManager.NameNotFoundException e) {
            sendmsg(context, "getVerName异常" + e.getMessage());
        }
        return verName;
    }

    public static boolean isreg(Activity activity, String name) {
        Intent intent = new Intent();
        intent.setAction(name);
        PackageManager pm = activity.getPackageManager();
        List<ResolveInfo> resolveInfos = pm.queryBroadcastReceivers(intent, 0);
        if (resolveInfos != null && !resolveInfos.isEmpty()) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 判断某activity是否处于栈顶
     *
     * @return true在栈顶 false不在栈顶
     */
    public static int isActivityTop(Context context) {
        try {
            ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
            List<RunningServiceInfo> sinfos = manager.getRunningServices(100);
            for (RunningServiceInfo info : sinfos) {
            }
            List<RunningTaskInfo> infos = manager.getRunningTasks(100);
            for (RunningTaskInfo runningTaskInfo : infos) {
                if (runningTaskInfo.topActivity.getClassName()
                        .equals("cooperation.qwallet.plugin.QWalletPluginProxyActivity")) {
                    return runningTaskInfo.numActivities;
                }
            }
            return 0;
        } catch (SecurityException e) {
            sendmsg(context, e.getMessage());
            return 0;
        }
    }

    public static String getAlipayLoginId(ClassLoader classLoader) {
        String loginId = "";
        try {
            Class<?> AlipayApplication = XposedHelpers.findClass("com.alipay.mobile.framework.AlipayApplication",
                    classLoader);
            Class<?> SocialSdkContactService = XposedHelpers
                    .findClass("com.alipay.mobile.personalbase.service.SocialSdkContactService", classLoader);
            Object instace = XposedHelpers.callStaticMethod(AlipayApplication, "getInstance");
            Object MicroApplicationContext = XposedHelpers.callMethod(instace, "getMicroApplicationContext");
            Object service = XposedHelpers.callMethod(MicroApplicationContext, "findServiceByInterface",
                    SocialSdkContactService.getName());
            Object MyAccountInfoModel = XposedHelpers.callMethod(service, "getMyAccountInfoModelByLocal");
            String userId = XposedHelpers.getObjectField(MyAccountInfoModel, "userId").toString();
            loginId = userId;
        } catch (Exception e) {
        }
        return loginId;
    }

    public static String getAlipayLoginAccount(ClassLoader classLoader) {
        String loginId = "";
        try {
            Class<?> AlipayApplication = XposedHelpers.findClass("com.alipay.mobile.framework.AlipayApplication",
                    classLoader);
            Class<?> SocialSdkContactService = XposedHelpers
                    .findClass("com.alipay.mobile.personalbase.service.SocialSdkContactService", classLoader);
            Object instace = XposedHelpers.callStaticMethod(AlipayApplication, "getInstance");
            Object MicroApplicationContext = XposedHelpers.callMethod(instace, "getMicroApplicationContext");
            Object service = XposedHelpers.callMethod(MicroApplicationContext, "findServiceByInterface", SocialSdkContactService.getName());
            Object MyAccountInfoModel = XposedHelpers.callMethod(service, "getMyAccountInfoModelByLocal");
            loginId = XposedHelpers.getObjectField(MyAccountInfoModel, "loginId").toString();
        } catch (Exception e) {
        }
        return loginId;
    }

    /*public static String getWechatLoginId(Context context) {
        String loginId = "";
        try {
            SharedPreferences sharedPreferences = context.getSharedPreferences("com.tencent.mm_preferences", 0);
            loginId = sharedPreferences.getString("login_user_name", "");
        } catch (Exception e) {
            PayHelperUtils.sendmsg(context, e.getMessage());
        }
        return loginId;
    }

    public static String getQQLoginId(Context context) {
        String loginId = "";
        try {
            SharedPreferences sharedPreferences = context.getSharedPreferences("Last_Login", 0);
            loginId = sharedPreferences.getString("uin", "");
        } catch (Exception e) {
            PayHelperUtils.sendmsg(context, e.getMessage());
        }
        return loginId;
    }*/

    public static void sendLoginId(String loginid, String loginAccount, String type, Context context) {
        Intent broadCastIntent = new Intent();
        broadCastIntent.setAction(LOGINIDRECEIVED_ACTION);
        broadCastIntent.putExtra("type", type);
        broadCastIntent.putExtra("loginid", loginid);
        broadCastIntent.putExtra("loginAccount", loginAccount);
        context.sendBroadcast(broadCastIntent);
    }


    public static void startAlipayMonitor(final Context context) {
        try {
            Timer timer = new Timer();
            TimerTask timerTask = new TimerTask() {
                @Override
                public void run() {
                    L.d("轮询获取订单数据...");
                    SpUtils.putString(context, "time", System.currentTimeMillis() / 1000 + "");
                    Intent intent1 = new Intent();
                    intent1.setAction(PayHelperUtils.ALIPAYSTART_ACTION);
                    context.sendBroadcast(intent1);
                }
            };
            int triggerTime = 12;
            timer.schedule(timerTask, 0, triggerTime * 1000);
        } catch (Exception e) {
            sendmsg(context, "startAlipayMonitor->>" + e.getMessage());
        }
    }
}
